export class StoreHelper {
  /*** 
   * 寻找最接近控制器且没满的Container
  */
  public static findClosestControllerNotFullContainer(room: Room) : StructureContainer | undefined{
    const containers = room.find(FIND_STRUCTURES, {
      filter: (structure) => {
        return structure.structureType === STRUCTURE_CONTAINER && structure.store.getFreeCapacity(RESOURCE_ENERGY) > 0;
      }
    });
    
    if (containers.length === 0) {
      return undefined;
    }
    
    const controller = room.controller;
    if (!controller) {
      return undefined;
    }
    
    let closestContainer: StructureContainer | undefined;
    let closestDistance = Infinity;
    
    for (const container of containers) {
      const distance = container.pos.getRangeTo(controller.pos);
      if (distance < closestDistance) {
        closestContainer = container as StructureContainer;
        closestDistance = distance;
      }
    }
    
    return closestContainer;
  }

  /**
   * 寻找最近的非空容器
   * @param creep Creep 实例
   * @returns 最近的非空容器，如果没有找到则返回 null
   */
  public static findClosestNotEmptyContainer(creep: Creep,blackIdList?:Array<string>): AnyStructure  | undefined{
    const containers = creep.room.find(FIND_STRUCTURES, {
      filter: (structure) => {
        if(structure.structureType === STRUCTURE_CONTAINER){
          if(structure.store.getUsedCapacity(RESOURCE_ENERGY) > 0){
            if(blackIdList === undefined || blackIdList.indexOf(structure.id) === -1){
              return structure;
            }
          }
        }
      },
    });
    if(containers.length > 0){
      let pos = creep.pos.findClosestByPath(containers);
      if(pos){
        return pos;
      }
    }
  }

  /**
   * 寻找最近的非空存储
   * @param creep Creep 实例
   * @returns 最近的非空存储，如果没有找到则返回 null
   */
  public static findClosestNotEmptyStorage(creep: Creep,blackIdList?:Array<string>): AnyStructure  | null{
    const storages = creep.room.find(FIND_STRUCTURES, {
      filter: (structure) => {
        if(structure.structureType === STRUCTURE_STORAGE){
          if(structure.store.getUsedCapacity(RESOURCE_ENERGY) > 0){
            if(blackIdList === undefined || blackIdList.indexOf(structure.id) === -1){
              return structure;
            }
          }
        }
      },
    });
  
    // 根据存储的数量判断是否找到非空存储
    return storages.length > 0 ? creep.pos.findClosestByPath(storages) : null;
  }

  /**
   * 寻找附近掉落的
   * @param creep 
   */
  public static findClosestDroppedResources(creep: Creep){
    const resources = creep.room.find(FIND_DROPPED_RESOURCES);
    if(resources.length > 0){
      let pos = creep.pos.findClosestByPath(resources);
      if(pos){
        return pos;
      }
    }
  }
}